# -*- coding: utf-8 -*-
# ****************************************************
# Author: yizuoliang
# Create: 2024/6/24
# Last Modified: 2024/6/24
# Last Editor:
# Filename: user_controller.py
# Description: 用户接口层
# ***************************************************

from flask import Blueprint, request, jsonify
from flask_login import login_user, login_required

from applications.common.app_exception import AppException
from applications.common.constants.status_codes import ResponseCode
from applications.common.utils.response import response_wrapper
from applications.models.user import User
from flask_login import login_required, current_user

bp = Blueprint('user', __name__, url_prefix='/user')


# 用户分页查询
@bp.get('/data')
@response_wrapper
@login_required
def data():
    ditc = {'username': '易佐良', 'uid': 11}
    return ditc


@bp.post('/save')
def save():
    req_json = request.get_json(force=True)
    return req_json


@bp.post('/login')
@response_wrapper
def login_post():
    req = request.form
    username = req.get('username')
    password = req.get('password')
    # 未传入用户名密码
    if not username or not password:
        raise AppException(ResponseCode.USER_NO_ENTERED_USERNAME_PASSWORD.code,
                           ResponseCode.USER_NO_ENTERED_USERNAME_PASSWORD.message)
    user = User(12, username, password, 1)
    if not User:
        raise AppException(ResponseCode.USER_NOT_FOUND.code, ResponseCode.USER_NOT_FOUND.message)
    if user.enable == 0:
        raise AppException(ResponseCode.USER_DISABLED.code, ResponseCode.USER_DISABLED.message)
    login_user(user)
    return "登录成功"


@bp.get('/current_user')
@response_wrapper
@login_required
def get_current_user():
    if current_user.is_authenticated:
        user = User.from_current_user()
        return user.to_dict()
    raise AppException(ResponseCode.UNAUTHORIZED.code, ResponseCode.UNAUTHORIZED.message)
